package com.example.casper.jnuexperiment2025;

import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView.AdapterContextMenuInfo;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.fragment.app.FragmentActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.casper.jnuexperiment2025.dataop.BookDataOperator;

import java.util.ArrayList;
import java.util.List;

public class Hello02959Activity extends FragmentActivity {
    private RecyclerView recyclerView;
    private RecyclerViewBookAdapter adapter;
    private List<Book> books;
    private int selectedPosition = -1;
    
    // ActivityResultLauncher用于处理ActivityResult
    private ActivityResultLauncher<Intent> addBookLauncher;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_hello02959);
        
        // 初始化数据
        books = BookDataOperator.loadBooks(this);
        
        // 初始化RecyclerView
        recyclerView = findViewById(R.id.recycler_view_my_books);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new RecyclerViewBookAdapter(books);
        recyclerView.setAdapter(adapter);
        
        // 注册上下文菜单
        registerForContextMenu(recyclerView);
        
        // 初始化ActivityResultLauncher
        addBookLauncher = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                result -> {
                    if (result.getResultCode() == BookDetailsActivity.RESULT_ADD) {
                        // 添加新书
                        Intent data = result.getData();
                        if (data != null) {
                            String title = data.getStringExtra(BookDetailsActivity.EXTRA_BOOK_TITLE);
                            String price = data.getStringExtra(BookDetailsActivity.EXTRA_BOOK_PRICE);
                            
                            // 在选中位置后添加新书
                            Book newBook = new Book(title, price, R.drawable.book_no_name);
                            if (selectedPosition >= 0 && selectedPosition < books.size()) {
                                books.add(selectedPosition + 1, newBook);
                            } else {
                                books.add(newBook);
                            }
                            adapter.notifyItemInserted(selectedPosition + 1);
                            // 保存数据到文件
                            BookDataOperator.saveBooks(Hello02959Activity.this, books);
                        }
                    } else if (result.getResultCode() == BookDetailsActivity.RESULT_UPDATE) {
                        // 更新书籍信息
                        Intent data = result.getData();
                        if (data != null && selectedPosition >= 0 && selectedPosition < books.size()) {
                            String title = data.getStringExtra(BookDetailsActivity.EXTRA_BOOK_TITLE);
                            String price = data.getStringExtra(BookDetailsActivity.EXTRA_BOOK_PRICE);
                            
                            Book book = books.get(selectedPosition);
                            book.setPrice(price);
                            // 注意：这里简化处理，实际应该提供修改书名的功能
                            
                            adapter.notifyItemChanged(selectedPosition);
                            // 保存数据到文件
                            BookDataOperator.saveBooks(Hello02959Activity.this, books);
                        }
                    }
                });
    }
    
    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.context_menu_books, menu);
    }
    
    @Override
    public boolean onContextItemSelected(MenuItem item) {
        AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
        selectedPosition = (int) info.id;
        
        int itemId = item.getItemId();
        
        if (itemId == R.id.menu_add) {
            // 添加书籍
            Intent addIntent = new Intent(Hello02959Activity.this, BookDetailsActivity.class);
            addBookLauncher.launch(addIntent);
            return true;
        } else if (itemId == R.id.menu_update) {
            // 更新书籍
            if (selectedPosition >= 0 && selectedPosition < books.size()) {
                Book book = books.get(selectedPosition);
                Intent updateIntent = new Intent(Hello02959Activity.this, BookDetailsActivity.class);
                updateIntent.putExtra(BookDetailsActivity.EXTRA_BOOK_TITLE, book.getTitle());
                updateIntent.putExtra(BookDetailsActivity.EXTRA_BOOK_POSITION, selectedPosition);
                addBookLauncher.launch(updateIntent);
            }
            return true;
        } else if (itemId == R.id.menu_delete) {
            // 删除书籍
            showDeleteConfirmationDialog();
            return true;
        } else {
            return super.onContextItemSelected(item);
        }
    }
    
    private void showDeleteConfirmationDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("确认删除");
        builder.setMessage("确定要删除这本图书吗？");
        builder.setPositiveButton("确定", (dialog, which) -> {
            if (selectedPosition >= 0 && selectedPosition < books.size()) {
                books.remove(selectedPosition);
                adapter.notifyItemRemoved(selectedPosition);
                // 保存数据到文件
                BookDataOperator.saveBooks(Hello02959Activity.this, books);
            }
        });
        builder.setNegativeButton("取消", (dialog, which) -> dialog.dismiss());
        builder.create().show();
    }

    public List<Book> getListBooks() {
        List<Book> books = new ArrayList<>();
        books.add(new Book("无名之书", "29.99", R.drawable.book_no_name));
        books.add(new Book("软件项目管理案例教程（第3版）", "45.50", R.drawable.book_2));
        books.add(new Book("信息安全数学基础（第2版）", "38.00", R.drawable.book_1));
        return books;
    }
}